//
//  ComposeNoteView.swift
//  SSNote
//
//  Created by shen on 2023/10/17.
//

import CoreData
import SwiftUI

struct ComposeNoteView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @Environment(\.dismiss) private var dismiss

    @ObservedObject var note: Note

    @State private var title = ""
    @State private var noteBody = ""

    init(note: Note) {
        self.note = note
        title = note.title ?? ""
        noteBody = note.body ?? ""
        print(note)
    }

    var body: some View {
        print("GGG")
        return Form {
            Section {
                TextField(text: $title, prompt: Text("Place input title...")) {
                    Text("Title")
                }
                .font(.body)
            } header: {
                Text("title")
                    .font(.headline)
                    .bold()
            }

            Section {
                TextField(text: $noteBody, prompt: Text("Place input note...")) {
                    Text("Note")
                }
                .font(.body)
                .frame(maxHeight: 100)
                .lineLimit(0)
            } header: {
                Text("Your Note")
                    .font(.headline)
                    .bold()
            }
        }
        .navigationTitle("Add Note")
        .toolbar {
            Button {
                saveNote()
            } label: {
                Text("Save")
            }
            .disabled(title.isEmpty || noteBody.isEmpty)
        }
    }

    private func saveNote() {
        if note.id != nil {
            note.title = title
            note.body = noteBody
            note.modified = Date()
        } else {
            let note = Note(context: viewContext)
            note.id = UUID()
            note.title = title
            note.body = noteBody
            note.created = Date()
        }
        do {
            try viewContext.save()
        } catch {
            print("Save Core Data Error: \(error)")
        }

        dismiss()
    }
}
